<template>
  <div class="page">
    <layout-card :filters="filterOptions" @search-change="searchChange" @search-reset="searchReset" headtitle="数据筛选">
        <template #action >
          <el-button type="primary" @click="exportKnow" :loading="exportLoading" :disabled="exportLoading">导出</el-button>
        </template>
        <table-common ref="tableRef1" :columns="columns" :loading="loading" :pagination="pager" :table-data="tableData"
            size="large" @current-change="currentChange" @size-change="sizeChange" style="margin-top: 12px;" @sort-change="sortChange">
            <template #type="{ row }">
              <span>{{ row ? dicFormatter(eventTypeOption,row.type) : ''}}</span>
            </template>
            <template #eventLevel="{ row }">
              <span>{{ row ? dicFormatter(eventLevelOption,row.eventLevel) : ''}}</span>
            </template>
            
            <template #status="{ row }">
              <span>{{ row ? dicFormatter(searchStatusOption,row.status) : ''}}</span>
            </template>
            <template #reportCreator="{ row }">
              <span>{{ row.reportCreator.name}}</span>
            </template>
            <template #processGroup="{ row }">
              <span>{{ row.processGroup.name}}</span>
            </template>
            <template #action="{ row }">
              <!-- 40-待提交 41-待复核 42-已驳回 43-已通过 -->
              <el-button link type="primary" @click="goDetail(row,row.status,'detail')">查看</el-button>
              <el-button v-if="row.status===40 && currentUserId!=row.reportCreator.id" class="link-btn" link type="primary" @click="goDetail(row,row.status,'submit')">提交</el-button>
              <el-button v-if="row.status===41 && currentUserId!=row.reportCreator.id&&currentUserId!=row.submitPerson" class="link-btn" link type="primary" @click="goDetail(row,row.status,'review')">复核</el-button>
              <!-- 只有状态是已驳回且登录人是这条数据的提交人才能编辑 -->
              <el-button v-if="row.status===42 && currentUserId===row.submitPerson"  class="link-btn" link type="primary" @click="goDetail(row,row.status,'edit')">编辑</el-button>
            </template>
        </table-common>
    </layout-card>
  </div>
</template>

<script lang="ts" setup>
import {
  PageListType,
  getPageList,
  getCooperateEventType,
  exportList
} from '@/api/event/know'
import dicFormatter from '@/hooks/commonUtil'
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import {getResource} from "@/api/resource";
import { ElMessage , dayjs} from 'element-plus'
import { ref,reactive,onBeforeMount,onUnmounted} from 'vue'
import { filterOptions,cooperateEventTypeOption,commonEventTypeOption, searchStatusOption, eventLevelOption,eventTypeOption } from './config/filter'
import { columns } from './config/columns'
import router from '@/router';
import { useStore } from "vuex";
import { getUserInfo } from '@/api/eqpt/houseManger'
// import { cloneDeep } from 'lodash'

const store = useStore();
interface Search {
  type?: string
  eventTypeId?:string[]
  eventLevel?:string
  process_group_id?: string
  reportCreatorName?:string
  occurDate?: string[]
  handTime?: string[]
  status?: string
}
interface OrderItem {
  column?: string
  method?: string
}
const fillAndDetailRef=ref();
const search = ref<Search>({})
const order = ref([] as OrderItem[])
const loading = ref(false)
const tableData:any = ref([])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const userInfo:any = store.getters['user/getUserInfo'];
const isManager = store.getters['user/getIsManager'];
const currentUserId = userInfo.userId
// 加载字典
function loadDict() {
  getUserInfo({}).then((res:any)=>{
    filterOptions.value[4].inputProps.options = res.data.map((item:any)=>{
      return {
        value: item.userId,
        label: item.name
      }
    })
  })
  const tree = store.getters['user/getOrganTree'];
  
  filterOptions.value[3].inputProps.data=tree
  Promise.all([
    getResource('event_know_type'),
    getResource('event_common_type'),
    getResource('event_rules_event_level')
  ]).then(([
            res1,
            res2,
            res3
          ]) => {
            filterOptions.value[0].inputProps.options = res1.data.properties.meta;
            eventTypeOption.value = res1.data.properties.meta;
            commonEventTypeOption.value = res2.data.properties.meta;
            filterOptions.value[2].inputProps.options = res3.data.properties.meta;
            eventLevelOption.value = res3.data.properties.meta;
          })
}
// 加载 协同事件类型顶层
function loadCooperateEventType(){
  getCooperateEventType({}).then((res:any)=>{
    cooperateEventTypeOption.value = res.data.map((item:any)=>{
      return {
        value: item.id,
        label: item.name
      }
    })
  })
}
/**
 * 点击重置
 * @param data 数据
 */
const tableRef1=ref();
const searchReset = (data: FilterDataType) => {
  filterOptions.value[1].isDisabled=true;
  order.value=[];
  tableRef1.value.clearSort()
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  loadData()
}

const loadData = async() => {
  loading.value = true
  const { type, eventTypeId, eventLevel, reportCreatorName, status, occurDate, handTime, process_group_id } = search.value
  const payload: PageListType = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
      type,
      eventTypeId:eventTypeId?.length===0?undefined:eventTypeId,
      eventLevel,
      process_group_id: isManager ? process_group_id : userInfo.organId,
      reportCreatorName,
      status,
    },
    order:order.value.length? order.value:undefined
  }
  if(!occurDate || occurDate?.length === 0){
    payload.condition.eventTimeBegin = undefined
    payload.condition.eventTimeEnd = undefined
  }else{
    payload.condition.eventTimeBegin = occurDate[0]
    payload.condition.eventTimeEnd = occurDate[1]
  }
  if(!handTime || handTime?.length === 0){
    payload.condition.handTimeBegin = undefined
    payload.condition.handTimeEnd = undefined
  }else{
    payload.condition.handTimeBegin = handTime[0]
    payload.condition.handTimeEnd = handTime[1]
  }
  
  getPageList(payload).then((res:any)=>{
    tableData.value = res.data.list
    pager.total = res.data.total
  }).catch((err: any) => {
    ElMessage.error(err?.message || '查询失败')
  }).finally(()=>{
    loading.value=false;
  })
}

// 分页
const sizeChange = (size: number) => {
  pager.currentPage = 1,
  pager.pageSize = size
  loadData()
}
const currentChange = (value: number) => {
  pager.currentPage = value
  loadData()
}

/**
 * 点击查询
 */
const searchChange = (data: FilterDataType) => {
  pager.currentPage = 1,
  search.value = data
  loadData()
}
// 排序 
function sortChange(column:any){
  pager.currentPage = 1;
  const method = column.order==='descending'?'desc':'asc'
  order.value=[{ column: column.prop, method, }]
  loadData()
}

const exportLoading=ref(false);
const exportKnow = () => {
  exportLoading.value = true;
  const { type, eventTypeId, eventLevel, reportCreatorName, status, occurDate, handTime, process_group_id } = search.value
  const payload: any = {
    // pageNum: pager.currentPage,
    // pageSize: pager.pageSize,
    condition: {
      type,
      eventTypeId:eventTypeId?.length===0?undefined:eventTypeId,
      eventLevel,
      process_group_id: isManager ? process_group_id : userInfo.organId,
      reportCreatorName,
      status,
    },
    order:order.value.length? order.value:undefined
  }
  if(!occurDate || occurDate?.length === 0){
    payload.condition.eventTimeBegin = undefined
    payload.condition.eventTimeEnd = undefined
  }else{
    payload.condition.eventTimeBegin = occurDate[0]
    payload.condition.eventTimeEnd = occurDate[1]
  }
  if(!handTime || handTime?.length === 0){
    payload.condition.handTimeBegin = undefined
    payload.condition.handTimeEnd = undefined
  }else{
    payload.condition.handTimeBegin = handTime[0]
    payload.condition.handTimeEnd = handTime[1]
  }
  exportList(payload)
    .then((res:any) => {
      const link = document.createElement('a')
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute(
        'download',
        `事件知识库管理${dayjs().format('YYYY-MM-DD')}.xlsx`
      )
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
    .catch((err: any) => {
      const reader = new FileReader();
      reader.readAsText(err,'utf-8');
      reader.onload=()=>{
        try{
          const json = JSON.parse(reader.result as string);
          ElMessage.error(json?.message || '导出失败')
        } catch(e){
      } 
      }
    })
    .finally(()=>{
      exportLoading.value=false;
    })
}
// 跳转
function goDetail(row:any,status:number,type:string){
  router.push({ path: '/event/detailEdit', query: { id: row.id,status,type } })
}



const initData = () => {
  loadDict()
  loadCooperateEventType();
  loadData()
}

onBeforeMount(initData)
onUnmounted(()=>{
  filterOptions.value[1].isDisabled=true;
})

</script>
<style lang="less" scoped>
.card-box {
  padding: 24px;
  margin: 12px;
  background-color: #fff;
  border-radius: 8px;
}
.radio-group-task {
  margin-left: 24px;
}
.bread {
  padding: 20px 0 0 12px;
}
</style>

